package com.youku.expression;

import org.junit.Assert;

import com.youku.expression.ast.Ast;
import com.youku.expression.environment.Environment;
import com.youku.expression.environment.EnvironmentFactory;

/**
 * 解释器
 * 
 * @author loda
 *
 */
public class NormalInterpreter implements Interpreter{

	/**
	 * 解析表达式
	 * 
	 * @param projectId
	 *            表达式所属项目id
	 * @param caseId
	 *            表达式所在测试用例id(如果没有就为null)
	 * @param input
	 *            表达式字符串
	 * @return 表达式执行结果
	 */
	@Override
	public Object interpreter(Position position, String input) {
		Tokenizer tokenizer = new Tokenizer(input);
		tokenizer.process();

		Parser parser = new Parser(tokenizer);
		parser.process();

		Ast root = parser.tree();
		
		Assert.assertNotNull("所属项目编号不能为空", position.getProjectId());

		Environment environment = EnvironmentFactory.getEnvironment(position.getProjectId());

		//如果caseId不为空，表示该解析语句在这个测试用例中，则创建测试用例级别的环境
		String caseId=position.getCaseId();
		if (caseId != null)
			environment = environment.getEnvironment(caseId);
		
		return root.eval(environment);
	}

}
